<template>
  <div class="course-time-selector">
    <el-card class="time-selector-card">
      <template #header>
        <div class="card-header">
          <span>课程时间选择</span>
          <el-tooltip
            content="请选择上课时间，可多选"
            placement="top"
          >
            <el-icon class="header-icon"><InfoFilled /></el-icon>
          </el-tooltip>
        </div>
      </template>
      <div class="time-table">
        <el-table :data="timeTableData" border style="width: 100%">
          <el-table-column prop="period" label="节次" width="120" align="center">
            <template #default="scope">
              <div>
                第{{ scope.row.period }}节
                <div class="time-range">{{ scope.row.timeRange }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column 
            v-for="day in weekdays" 
            :key="day.value" 
            :label="day.label"
            align="center"
          >
            <template #default="scope">
              <el-checkbox
                v-model="selectedTimes[day.value-1][scope.row.period-1]"
                @change="handleTimeChange"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, watch } from 'vue'
import { InfoFilled } from '@element-plus/icons-vue'

export default {
  name: 'CourseTimeSelector',
  components: {
    InfoFilled,
  },
  props: {
    modelValue: {
      type: String,
      default: '{}',
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    // 定义周几数据
    const weekdays = [
      { value: 1, label: '周一' },
      { value: 2, label: '周二' },
      { value: 3, label: '周三' },
      { value: 4, label: '周四' },
      { value: 5, label: '周五' }
    ]

    // 定义时间段数据
    const timeRanges = [
      '08:00-09:50',
      '10:10-12:00',
      '14:10-16:00',
      '16:20-18:00',
      '19:00-20:50',
      '21:00-22:00'
    ]

    // 生成课程表数据
    const timeTableData = ref(
      Array.from({ length: 6 }, (_, i) => ({
        period: i + 1,
        timeRange: timeRanges[i],
      }))
    )

    // 创建一个5x6的二维数组来存储选中状态
    const selectedTimes = ref(
      Array(5).fill(null).map(() => Array(6).fill(false))
    )

    // 将字符串格式的时间数据转换为二维数组
   const parseTimeData = (timeString) => {
  try {
    const timeObj = typeof timeString === 'string' ? JSON.parse(timeString) : timeString
    const newSelectedTimes = Array(5).fill(null).map(() => Array(6).fill(false))

    Object.entries(timeObj).forEach(([day, periods]) => {
      const dayIndex = parseInt(day) - 1
      if (Array.isArray(periods)) {
        periods.forEach(period => {
          if (dayIndex >= 0 && dayIndex < 5 && period >= 1 && period <= 6) {
            newSelectedTimes[dayIndex][period - 1] = true
          }
        })
      }
    })

    return newSelectedTimes
  } catch (e) {
    console.error('时间数据解析错误:', e)
    return Array(5).fill(null).map(() => Array(6).fill(false))
  }
}

    // 将二维数组转换为字符串格式
    const generateTimeString = () => {
      const result = {}
      selectedTimes.value.forEach((day, dayIndex) => {
        const periods = day.reduce((acc, selected, periodIndex) => {
          if (selected) acc.push(periodIndex + 1)
          return acc
        }, [])
        if (periods.length > 0) {
          result[dayIndex + 1] = periods
        }
      })
       return result
    }

    // 处理时间选择变化
    const handleTimeChange = () => {
      const timeString = generateTimeString()
      emit('update:modelValue', timeString)
    }

    // 监听传入的值变化
    watch(() => props.modelValue, (newValue) => {
      selectedTimes.value = parseTimeData(newValue)
    }, { immediate: true })

    return {
      weekdays,
      timeTableData,
      selectedTimes,
      handleTimeChange
    }
  }
}
</script>

<style scoped>
.course-time-selector {
  width: 100%;
  margin: 0 auto;
}

.time-selector-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-icon {
  font-size: 16px;
  color: #909399;
  cursor: help;
}

.time-table {
  margin-top: 10px;
}

.time-range {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

:deep(.el-table) {
  --el-table-border-color: #DCDFE6;
  --el-table-header-bg-color: #F5F7FA;
}

:deep(.el-table th) {
  background-color: var(--el-table-header-bg-color);
  font-weight: bold;
}

:deep(.el-table td) {
  padding: 8px 0;
}

:deep(.el-checkbox) {
  margin-right: 0;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #EBEEF5;
  font-size: 16px;
  font-weight: bold;
}

.el-tooltip__trigger {
  cursor: help;
}

@media screen and (max-width: 768px) {
  .time-range {
    display: none;
  }

  :deep(.el-table td),
  :deep(.el-table th) {
    padding: 6px 0;
  }
}
</style>